package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.FailedLoginException;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    // 微信登录接口
    private final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;


    /**
     * @param userLoginDTO
     * @return UserLoginVO
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) throws FailedLoginException {
        // 1.请求wx登录接口  请求开发者服务器
        String code = userLoginDTO.getCode();
        String openid = getOpenid(code);
        log.info("openid 获取成功！{}",openid);
        // 非空判断
        if(ObjectUtil.isNull(openid)){ // 登录失败，获取openid 失败
            throw new FailedLoginException(MessageConstant.LOGIN_FAILED);
        }
        // 2.判断是否为新用户
        User user = userMapper.selectByOpenId(openid);
        // 是  实现自动注册
        if(ObjectUtil.isNull(user)){ // 未查询到，说明为新用户---自动注册
            // 构建新用户信息
            user=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 插入新用户信息
            userMapper.insert(user);
        }

        // 不是 构建登录信息返回
        // 3. 返回
        return user;
    }


    /**
     * 请求 微信 登录接口
     * @param code
     * @return
     */
    public String getOpenid(String code){
        // 构建请求参数
        HashMap<String,String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap); // 请求wx登录接口
        // 反序列化
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

}
